package cn.south.campus.business.service.impl;

import cn.south.campus.business.mapper.ConfigMapper;
import cn.south.campus.business.model.constants.CacheKey;
import cn.south.campus.business.model.entity.Config;
import cn.south.campus.business.model.enums.ConfigTypeEnums;
import cn.south.campus.business.service.ConfigService;
import cn.south.campus.common.cache.CacheService;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author chow
 * @since 2024-12-13
 */
@Service
@Slf4j
@AllArgsConstructor
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    private final CacheService cacheService;

    @PostConstruct
    public void init() {
        loadConfig();
    }

    @Override
    public void loadConfig() {
        List<Config> configList = list();
        if (configList == null || configList.isEmpty()) {
            return;
        }
        Map<String, String> configMap = configList.stream().collect(Collectors.toMap(Config::getConfigKey, JSON::toJSONString));
        cacheService.setCacheMap(CacheKey.CONFIG, configMap);
        log.info("load config success, configMap:{}", configMap);
    }

    @Override
    public boolean refreshConfig(String key) {
        Config config = getById(key);
        if (config == null) {
            return cacheService.deleteCacheMap(CacheKey.CONFIG, key);
        }
        cacheService.updateCacheMap(CacheKey.CONFIG, key, JSON.toJSONString(config));
        return true;
    }

    @Override
    public Object getConfig(String key) {
        String cacheMapValue = cacheService.getCacheMapValue(CacheKey.CONFIG, key);
        Config config = JSON.parseObject(cacheMapValue, Config.class);
        return ConfigTypeEnums.parseValGet(config);
    }
}
